package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //获取密码
        String password = employee.getPassword();
        //md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lqw);
        //对比用户名
        if (null == emp) {
            return R.error("用户名输入不存在");
            //对比密码
        } else if (false == emp.getPassword().equals(password)) {
            return R.error("密码输入错误");
            //对比账号状态
        } else if (emp.getStatus() == 0) {
            return R.error("账号已被禁用");
        } else {
            request.getSession().setAttribute("employee", emp.getId());
            return R.success(emp);
        }
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //删除session退出登录
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页插件
        Page pg = new Page(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        //模糊查询判断
        if (null != name) {
            lqw.like(Employee::getName, name);
        }
        //查询排序
        lqw.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pg, lqw);
        return R.success(pg);
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        //设置初始密码并md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("666666".getBytes()));
        employeeService.save(employee);
        return R.success("添加成功");
    }

    @PutMapping
    public R<String> updateByStatus(@RequestBody Employee employee) {
        employeeService.updateById(employee);
        return R.success("状态修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> selectById(@PathVariable Long id) {
        Employee byId = employeeService.getById(id);
        return R.success(byId);
    }
}
